<?php

class News_model extends CI_Model
{
	private $DB, $Mytile;

	public function __construct()
	{
		parent::__construct();
		$this->DB = $this->load->database('admin', TRUE);
		$this->Mytile = $this->load->dbutil($this->DB, TRUE); //加载数据库文件类
	}



	/**
	 * 访问数据库，写入文章内容
	 * $title            post文章标题
	 * $introduction    post文章简介
	 * $time            post文章时间
	 * $content        post文章内容
	 */
	public function write_news_mysql($title, $title_url, $introduction, $time, $content,$category)
	{
		$this->DB->reconnect();
		$sql = "INSERT INTO news (title,title_url,introduction,time,content,category)VALUES('$title','$title_url','$introduction','$time','$content','$category');";
		$this->DB->query($sql);
		if ($this->DB->affected_rows() != 0) {
			return true;
		}
		return false;
	}

	/**
	 * 读取最新文章列表
	 */
	public function read_new_news_mysql($page, $rows)
	{
		$this->DB->reconnect();
		//检查数据库是否存在此用户名
		$query = $this->DB->query("SELECT * FROM news  ORDER BY time DESC LIMIT $page,$rows ;");
		$newslist = array();
		if ($this->DB->affected_rows() == 0) {
			return null;
		}
		foreach ($query->result_array() as $row) {
			$newslist[] = $row;
		}
		return $newslist;
	}

	/**
	 * 读取文章一共的数量
	 * $name 传入的表名称
	 */
	public function news_count($name)
	{
		$this->DB->reconnect();
		//检查数据库是否存在此用户名
		$query = $this->DB->query("SELECT  COUNT(*) FROM $name;");
		$row = $query->row_array();
		$count = $row['COUNT(*)'];
		return $count;
	}

	/**
	 * 修改文章内容
	 * @param $id
	 * @param $title
	 * @param $title_url
	 * @param $introduction
	 * @param $time
	 * @param $content
	 *
	 */
	public function modify_news_mysql($id, $title, $title_url, $introduction, $time, $content,$category)
	{
		$this->DB->reconnect();
		//UPDATE runoob_tbl SET runoob_title='学习 C++' WHERE runoob_id=3;
		$query = $this->DB->query("UPDATE news SET title='$title',title_url='$title_url',introduction='$introduction',content='$content',category='$category',time='$time' WHERE id = $id;");
		if ($this->DB->affected_rows() != 0) {
			return true;
		}
		return false;
	}

	/**
	 * get传入id，返回指定id的文章
	 */
	public function id_news_mysql($id){
		$this->DB->reconnect();
		$query = $this->DB->query("SELECT * from news WHERE id = $id;");
		if ($this->DB->affected_rows() != 0) {
			$row = $query->row_array();
			return $row;
		}
		return null;
	}
}
